package com.itheimajdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

//JDBC API 详解：DriverManger
public class jdbcdemo_Connection{
    public static void main(String[] args) throws Exception{
        //注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接：(如果是本地的mysql并且端口号默认的3306可以简化书写)
        String url = "jdbc:mysql://localhost:3306/mysql";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url,username,password);
        //3.定义sql
        String sql1 = "update demo set money = 300 where id = 1";
        String sql2 = "update demo set money = 200 where id = 2";
        //4.获取执行sql的对象Statement
        Statement stmt = conn.createStatement();

        //开启事务


        try {
            //开启事务
            conn.setAutoCommit(false);
            //5.执行sql
            int count1 = stmt.executeUpdate(sql1);
            //6.处理结果
            System.out.println(count1);
            int i =3/0;
            //5.执行sql
            int count2 = stmt.executeUpdate(sql2);
            //6.处理结果
            System.out.println(count2);

            //提交事务
            conn.commit();
        } catch (Exception throwables) {
            //回滚事务
            conn.rollback();
            throw new RuntimeException();
        }

        //提交事务


        //7.释放资源

        stmt.close();
        conn.close();
    }
}